package generate.generatecode;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import com.tre.jdevtemplateboot.common.util.JasyptUtils;
import com.tre.jdevtemplateboot.exception.global.SysBusinessException;
import org.jasypt.exceptions.EncryptionOperationNotPossibleException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.awt.*;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @program: jdev-boot-core
 * @description
 * @author: JDev
 * @create: 2021-08-04 15:09
 **/
public class GeneratorAutoCode {

    private static final Logger logger = LoggerFactory.getLogger(GeneratorAutoCode.class);
    private static final String DEFAULT_PACKAGE_NAME = "com.tre.jdevtemplateboot";
    private static StrategyConfig strategyConfig = null;

    private GeneratorAutoCode(){

    }

    /**
     * 代码生成,数据库中的全部实体表
     * @param buildPath  生成路径
     * @param dbType  数据库类型 枚举(enum)
     * @param driverName  数据库驱动
     * @param url  数据库服务器地址和数据库名
     * @param userName  数据库用户
     * @param password  数据库密码
     * @throws Exception
     */
    public static void generator(String buildPath, DbType dbType, String driverName, String url, String userName
            ,String password) throws SysBusinessException, IOException  {

        strategyConfig = new StrategyConfig();
        strategyConfig.setNaming(NamingStrategy.underline_to_camel)
            .setColumnNaming(NamingStrategy.underline_to_camel)
            .setRestControllerStyle(true)
            .setControllerMappingHyphenStyle(true)
            .setTablePrefix(new PackageConfig().getModuleName() + "_");
        // 带命名策略的代码生成处理
        codeGeneratorService(buildPath, dbType, driverName, url, userName, password, strategyConfig, DEFAULT_PACKAGE_NAME);
    }

    /**
     * 代码生成,数据库中的全部实体表
     * @param buildPath  生成路径
     * @param dbType  数据库类型 枚举(enum)
     * @param driverName  数据库驱动
     * @param url  数据库服务器地址和数据库名
     * @param userName  数据库用户
     * @param password  数据库密码
     * @param tableNames  多个表名传数组
     * @throws SysBusinessException
     */
    public static void generator(String buildPath, DbType dbType, String driverName, String url, String userName
            ,String password, String[] tableNames) throws SysBusinessException, IOException  {

        strategyConfig = new StrategyConfig();
        strategyConfig.setNaming(NamingStrategy.underline_to_camel)
            .setColumnNaming(NamingStrategy.underline_to_camel)
            .setRestControllerStyle(true)
            .setControllerMappingHyphenStyle(true)
            .setTablePrefix(new PackageConfig().getModuleName() + "_")
            .setInclude(tableNames);

        // 带命名策略的代码生成处理
        codeGeneratorService(buildPath, dbType, driverName, url, userName, password, strategyConfig,DEFAULT_PACKAGE_NAME);
    }


    /**
     * 代码生成,数据库中的全部实体表
     * @param buildPath  生成路径
     * @param dbType  数据库类型 枚举(enum)
     * @param driverName  数据库驱动
     * @param url  数据库服务器地址和数据库名
     * @param userName  数据库用户
     * @param password  数据库密码
     * @param tableNames  多个表名传数组
     * @param include  true：需要生成的表 , false：排除生成的表
     * @throws Exception
     */
    public static void generator(String buildPath, DbType dbType, String driverName, String url, String userName
            ,String password, String[] tableNames, Boolean include) throws SysBusinessException, IOException  {

        strategyConfig = new StrategyConfig();
        strategyConfig.setNaming(NamingStrategy.underline_to_camel)
            .setColumnNaming(NamingStrategy.underline_to_camel)
            .setRestControllerStyle(true)
            .setControllerMappingHyphenStyle(true)
            .setTablePrefix(new PackageConfig().getModuleName() + "_");
        if (include) {
            strategyConfig.setInclude(tableNames);
        } else {
            strategyConfig.setExclude(tableNames);
        }
        // 带命名策略的代码生成处理
        codeGeneratorService(buildPath, dbType, driverName, url, userName, password, strategyConfig, DEFAULT_PACKAGE_NAME);
    }

    /**
     * 代码生成,数据库中的全部实体表
     * @param buildPath  生成路径
     * @param dbType  数据库类型 枚举(enum)
     * @param driverName  数据库驱动
     * @param url  数据库服务器地址和数据库名
     * @param userName  数据库用户
     * @param password  数据库密码
     * @param packageName  项目包名
     * @throws Exception
     */
    public static void generator(String buildPath, DbType dbType, String driverName, String url, String userName
            ,String password, String packageName) throws SysBusinessException, IOException  {

        strategyConfig = new StrategyConfig();
        strategyConfig.setNaming(NamingStrategy.underline_to_camel)
                .setColumnNaming(NamingStrategy.underline_to_camel)
                .setRestControllerStyle(true)
                .setControllerMappingHyphenStyle(true)
                .setTablePrefix(new PackageConfig().getModuleName() + "_");
        // 带命名策略的代码生成处理
        codeGeneratorService(buildPath, dbType, driverName, url, userName, password, strategyConfig, packageName);
    }

    /**
     * 代码生成,数据库中的全部实体表
     * @param buildPath  生成路径
     * @param dbType  数据库类型 枚举(enum)
     * @param driverName  数据库驱动
     * @param url  数据库服务器地址和数据库名
     * @param userName  数据库用户
     * @param password  数据库密码
     * @param tableNames  多个表名传数组
     * @param packageName  项目包名
     * @throws Exception
     */
    public static void generator(String buildPath, DbType dbType, String driverName, String url, String userName
            ,String password, String[] tableNames, String packageName) throws SysBusinessException, IOException  {

        strategyConfig = new StrategyConfig();
        strategyConfig.setNaming(NamingStrategy.underline_to_camel)
                .setColumnNaming(NamingStrategy.underline_to_camel)
                .setRestControllerStyle(true)
                .setControllerMappingHyphenStyle(true)
                .setTablePrefix(new PackageConfig().getModuleName() + "_")
                .setInclude(tableNames);

        // 带命名策略的代码生成处理
        codeGeneratorService(buildPath, dbType, driverName, url, userName, password, strategyConfig,packageName);
    }

    /**
     * 代码生成,数据库中的全部实体表
     * @param buildPath  生成路径
     * @param dbType  数据库类型 枚举(enum)
     * @param driverName  数据库驱动
     * @param url  数据库服务器地址和数据库名
     * @param userName  数据库用户
     * @param password  数据库密码
     * @param tableNames  多个表名传数组
     * @param include  true：需要生成的表 , false：排除生成的表
     * @param packageName  项目包名
     * @throws Exception
     */
    public static void generator(String buildPath, DbType dbType, String driverName, String url, String userName
            ,String password, String[] tableNames, Boolean include, String packageName) throws SysBusinessException, IOException {

        strategyConfig = new StrategyConfig();
        strategyConfig.setNaming(NamingStrategy.underline_to_camel)
                .setColumnNaming(NamingStrategy.underline_to_camel)
                .setRestControllerStyle(true)
                .setControllerMappingHyphenStyle(true)
                .setTablePrefix(new PackageConfig().getModuleName() + "_");
        if (include) {
            strategyConfig.setInclude(tableNames);
        } else {
            strategyConfig.setExclude(tableNames);
        }
        // 带命名策略的代码生成处理
        codeGeneratorService(buildPath, dbType, driverName, url, userName, password, strategyConfig, packageName);

    }


    /**
     *
     * @param buildPath
     * @param dbType
     * @param driverName
     * @param url
     * @param userName
     * @param password
     * @param strategyConfig
     * @param packageName
     * @throws Exception
     */
    private static void codeGeneratorService(final String buildPath, DbType dbType, String driverName, String url
            , String userName, String password, StrategyConfig strategyConfig, String packageName) throws SysBusinessException, IOException {

        if (!CheckBuildDirectory.checkExistFile(buildPath)) {
            return;
        }
        // 代码生成器
        AutoGenerator mpg = new AutoGenerator();
        // 全局配置
        GlobalConfig gc = new GlobalConfig();
        gc.setOutputDir(buildPath + "/src/main/java")
                .setAuthor("JDev")
                .setOpen(false);

        mpg.setGlobalConfig(gc);
        String decyptPwd;
        try {
            decyptPwd = JasyptUtils.decyptPwd(password);
        } catch (EncryptionOperationNotPossibleException ex) {
            throw new EncryptionOperationNotPossibleException("请使用工具类TreDBPasswordTool，对数据库密码加密后，再次运行自动生成。");
        }

        // 数据源配置
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl(url)
                .setDriverName(driverName)
                .setUsername(userName)
                .setPassword(decyptPwd)
                .setDbType(dbType);
        mpg.setDataSource(dsc);

        // 包配置
        PackageConfig pc = new PackageConfig();
        pc.setParent(packageName)
                .setEntity("domain.po")
                .setController("web.controller");
        mpg.setPackageInfo(pc);

        // 自定义配置
        InjectionConfig cfg = new InjectionConfig() {
            @Override
            public void initMap() {
                // to do nothing
            }
        };
        List<FileOutConfig> focList = new ArrayList<>();
        focList.add(new FileOutConfig("/templates/mapper.xml.ftl") {
            @Override
            public String outputFile(TableInfo tableInfo) {
                // 自定义输入文件名称
                return buildPath + "/src/main/resources/mapper/" + "/" + tableInfo.getEntityName() + "Mapper"
                        + StringPool.DOT_XML;
            }
        });
        cfg.setFileOutConfigList(focList);
        mpg.setCfg(cfg);
        mpg.setTemplate(new TemplateConfig().setXml(null));
        // 策略配置
        mpg.setStrategy(strategyConfig);
        mpg.setTemplateEngine(new FreemarkerTemplateEngine());
        mpg.execute();
        logger.info("生成成功，请复制目录{}下的内容到你的项目中。",buildPath);
        //打开生成
        Desktop.getDesktop().open(new File(buildPath));

    }


}
